<template>
  <div class="venues-container">
    <div class="page-header">
      <h2 class="page-title">场地预约</h2>
      <el-button type="primary" icon="el-icon-tickets" @click="showMyReservations">查看个人预约</el-button>
    </div>

    <el-row :gutter="20" class="venue-list">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="venue in venues" :key="venue.id">
        <transition name="fade-up" appear>
          <div class="venue-card" @click="selectVenue(venue)">
            <div class="venue-image" :style="{ backgroundImage: `url(${baseUrl}${jsonToString(venue.images).split(',')[0]})` }">
              <div class="venue-status" :class="{ 'available': venue.status === 1 }">
                {{ venue.status === 1 ? '可用' : '维护中' }}
              </div>
            </div>
            <div class="venue-info">
              <h3 class="venue-name">{{ venue.name }}</h3>
              <p class="venue-type">{{ venue.type }}</p>
              <div class="venue-details">
                <span><i class="el-icon-user"></i>容纳 {{ venue.capacity }} 人</span>
                <span><i class="el-icon-money"></i>¥{{ venue.price }}/天</span>
              </div>
              <p class="venue-address"><i class="el-icon-location"></i>{{ venue.address }}</p>
            </div>
          </div>
        </transition>
      </el-col>
    </el-row>

    <!-- 场地预约对话框 -->
    <el-dialog
      title="场地预约"
      :visible.sync="dialogVisible"
      width="50%"
      class="reservation-dialog"
    >
      <el-form :model="reservationForm" :rules="rules" ref="reservationForm" label-width="100px">
        <el-form-item label="场地名称">
          <span>{{ selectedVenue.name }}</span>
        </el-form-item>
        <el-form-item label="预约时间" prop="dateRange">
          <el-date-picker
            v-model="reservationForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参与人数" prop="participantCount">
          <el-input-number
            v-model="reservationForm.participantCount"
            :min="1"
            :max="selectedVenue.capacity"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="用途说明" prop="purpose">
          <el-input
            type="textarea"
            v-model="reservationForm.purpose"
            :rows="3"
            placeholder="请简要说明活动用途"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReservation">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 个人预约对话框 -->
    <el-dialog
      title="我的预约"
      :visible.sync="myReservationsVisible"
      width="70%"
      class="my-reservations-dialog"
    >
      <el-table :data="myReservations" style="width: 100%">
        <el-table-column prop="venueName" label="场地名称" width="180"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
        <el-table-column prop="participantCount" label="参与人数" width="100"></el-table-column>
        <el-table-column prop="purpose" label="用途说明" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 0 ? 'warning' : 'info'">
              {{scope.row.status === 1 ? '已确认' : scope.row.status === 0 ? '待审核' : '已取消' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              @click="cancelReservation(scope.row)"
              :disabled="scope.row.status !== 0 && scope.row.status !== 1"
            >取消预约</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {getAllVenue} from "@/api/reunion/venue";
import {listReservation, ueditReservation, ulistReservation, updateReservation} from "@/api/reunion/reservation";

export default {
  name: 'Venues',
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      venues: [
        // {
        //   id: 1,
        //   name: '阳光会议室',
        //   type: '会议室',
        //   capacity: 30,
        //   address: '科技园区A栋3层',
        //   price: 1000,
        //   status: 1,
        //   image: 'https://via.placeholder.com/300x200'
        // },
        // {
        //   id: 2,
        //   name: '户外拓展基地',
        //   type: '户外场地',
        //   capacity: 100,
        //   address: '郊区生态园',
        //   price: 3000,
        //   status: 1,
        //   image: 'https://via.placeholder.com/300x200'
        // },
        // {
        //   id: 3,
        //   name: '创意空间',
        //   type: '多功能厅',
        //   capacity: 50,
        //   address: '文化中心B区',
        //   price: 2000,
        //   status: 0,
        //   images: 'https://via.placeholder.com/300x200'
        // }
      ],
      dialogVisible: false,
      myReservationsVisible: false,
      selectedVenue: {},
      myReservations: [],
      reservationForm: {
        dateRange: [],
        participantCount: 1,
        purpose: ''
      },
      rules: {
        dateRange: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
        participantCount: [{ required: true, message: '请输入参与人数', trigger: 'blur' }],
        purpose: [{ required: true, message: '请输入用途说明', trigger: 'blur' }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  created() {
    this.getAllVenue()
  },
  methods: {
    jsonToString(jsonData) {
      if (!jsonData) return '';
      try {
        // 如果输入是字符串，先解析成数组
        const arr = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
        // 确保是数组
        if (Array.isArray(arr)) {
          return arr.join(',');
        }
        return '';
      } catch (e) {
        // 如果解析失败，返回空字符串
        return '';
      }
    },
    stringToJson(pathString) {
      if (!pathString) return '[]';
      // 将字符串按逗号分割成数组
      const pathArray = pathString.split(',');
      // 返回JSON字符串
      return JSON.stringify(pathArray);
    },
    getAllVenue(){
      getAllVenue().then(response => {
        console.log(response)
        this.venues = response.data
      })
    },
    selectVenue(venue) {
      this.$router.push(`/venue/${venue.id}`)
    },
    showReservationDialog() {
      this.dialogVisible = true
    },
    submitReservation() {
      this.$refs.reservationForm.validate(valid => {
        if (valid) {
          // TODO: 调用预约API
          this.$message.success('预约提交成功，请等待审核')
          this.dialogVisible = false
        }
      })
    },
    showMyReservations() {
      // 获取当前用户的预约列表
      ulistReservation({}).then(response => {
        const reservations = response.data || [];

        // 获取所有场地信息，用于匹配场地名称
        getAllVenue().then(venueResponse => {
          console.log('所有场地信息:', venueResponse.data);
          const venueMap = {};
          // 创建场地ID到场地名称的映射
          venueResponse.data.forEach(venue => {
            venueMap[venue.id] = venue;
          });

          // 为每条预约记录添加场地名称
          this.myReservations = reservations.map(reservation => {
            const venue = venueMap[reservation.venueId];
            return {
              ...reservation,
              venueName: venue ? venue.venueName : '未知场地'
            };
          });

          this.myReservationsVisible = true;
          console.log('处理后的预约列表:', this.myReservations);
        }).catch(error => {
          // 如果获取场地信息失败，仍然显示预约列表，但没有场地名称
          this.myReservations = reservations;
          this.myReservationsVisible = true;
          this.$message.warning('获取场地信息失败，无法显示场地名称');
          console.error('获取场地信息失败:', error);
        });
      }).catch(error => {
        this.$message.error('获取预约列表失败：' + error);
      })
    },
    cancelReservation(reservation) {
      this.$confirm('确认取消该预约吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 更新预约状态为已取消（假设状态码为2表示已取消）
        const data = {
          id: reservation.id,
          status: 2 // 已取消状态
        }
        ueditReservation(data).then(response => {
          this.$message.success('预约已取消')
          // 刷新预约列表
          this.showMyReservations()
        }).catch(error => {
          this.$message.error('取消预约失败：' + error)
        })
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.venues-container {
  animation: fadeIn 0.5s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 500;
    color: #2c3e50;
    margin: 0;
  }
}

.venue-list {
  margin: -10px;
}

.venue-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  margin: 10px;
  cursor: pointer;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
  }

  .venue-image {
    height: 200px;
    background-size: cover;
    background-position: center;
    position: relative;

    .venue-status {
      position: absolute;
      top: 12px;
      right: 12px;
      padding: 4px 8px;
      border-radius: 4px;
      background: #f56c6c;
      color: white;
      font-size: 12px;

      &.available {
        background: #67c23a;
      }
    }
  }

  .venue-info {
    padding: 16px;

    .venue-name {
      font-size: 18px;
      font-weight: 500;
      color: #2c3e50;
      margin: 0 0 8px;
    }

    .venue-type {
      color: #409EFF;
      font-size: 14px;
      margin: 0 0 12px;
    }

    .venue-details {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      color: #606266;
      font-size: 14px;

      i {
        margin-right: 4px;
      }
    }

    .venue-address {
      color: #909399;
      font-size: 14px;
      margin: 0;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;

      i {
        margin-right: 4px;
      }
    }
  }
}

// 动画
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.fade-up-enter-active {
  animation: fadeIn 0.5s ease-out;
}

.reservation-dialog, .my-reservations-dialog {
  .el-dialog__body {
    padding: 30px 20px;
  }
}

.my-reservations-dialog {
  .el-table {
    margin-bottom: 20px;
  }
}
</style>
